<template>
  <div>
    <el-form :inline="true" :model="searchForm" width="30%">
      <el-form-item label="用户姓名"><el-input v-model="searchForm.userName" placeholder="请输入用户姓名"/></el-form-item>
      <el-form-item label="备注"><el-input v-model="searchForm.remark" placeholder="请输入备注" /></el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>

    <el-button type="success" @click="refreshSystemUsers">刷新</el-button>
    <el-button type="success" @click="showDialog('addOrEditVisible')">新增</el-button>
    <el-button type="success" @click="deleteDatas">批量删除</el-button>

    <el-table :data="systemUser" style="width: 100%"
              @selection-change="selection => {selectedSystemUsers = selection;}">
      <el-table-column type="selection" width="30"/>
      <el-table-column prop="userId" label="ID" width="100" v-if="false"/>
      <el-table-column prop="loginName" label="登录名" width="100"/>
      <el-table-column prop="userName" label="用户姓名"/>
      <el-table-column prop="sex" label="性别"/>
      <el-table-column prop="age" label="年龄"/>
      <el-table-column prop="remark" label="备注"/>
      <el-table-column label="操作" width="260">
        <template #default="scope">
          <el-button type="success"
                     @click="showDialog('addOrEditVisible',najlForm,scope.row)">编辑
          </el-button>
          <el-button type="success" @click="deleteData(scope.row.userId, scope.row.userName)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-config-provider :locale="zhCn">
      <el-pagination style="display: flex; justify-content: flex-end; margin-top: 10px;"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="pagination.currentPage"
                     :page-sizes="[10, 20, 50, 100, 200, 1000,2000, 5000,10000]"
                     :page-size="pagination.pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="pagination.total"/>
    </el-config-provider>
    <el-dialog title="用户信息编辑" v-model="addOrEditVisible" width="30%"
               :close-on-click-modal="false" @close="closeDialog('addOrEditVisible')">
      <el-form ref="najlFormRef" :model="najlForm" :rules="rules">
        <el-form-item label="登录名" prop="loginName" label-width="100px">
          <el-input v-model="najlForm.loginName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="登录密码" prop="loginPswd" label-width="100px">
          <el-input v-model="najlForm.loginPswd" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户姓名" prop="userName" label-width="100px">
          <el-input v-model="najlForm.userName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户性别" prop="sex" label-width="100px">
          <el-select v-model="najlForm.sex" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age" label-width="100px">
          <el-input v-model="najlForm.age" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark" label-width="100px">
          <el-input v-model="najlForm.remark" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog('addOrEditVisible')">取 消</el-button>
          <el-button type="primary" @click="addOrUpdate">确 定</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import axios from 'axios';
import {ElMessageBox} from 'element-plus';
import {reactive, ref, onMounted, nextTick} from 'vue';
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import tableMaintain from './TableMaintain.vue';

export default {
  name: 'SystemUserList',
  setup() {
    const systemUser = ref([]);
    const searchForm = reactive({userName: '', remark: ''});
    const addOrEditVisible = ref(false);
    const najlForm = reactive({
      userId: 0,
      loginName: '',
      loginPswd: '',
      userName: '',
      sex: '男',
      age: '',
      remark: ''
    });
    const tableForm = reactive({
      userId: 0,
      tableName: '',
      tableComment: '',
      dbColumnReqList: [
        {
          columnName: 'userId',
          columnType: 'bigint',
          columnLength: 64,
          columnComment: '主键',
          required: true,
          editing: false
        },
        {
          columnName: 'create_user_id',
          columnType: 'varchar',
          columnLength: 64,
          columnComment: '创建用户ID',
          required: true,
          editing: false
        },
        {
          columnName: 'create_time',
          columnType: 'date',
          columnLength: 64,
          columnComment: '创建时间',
          required: true,
          editing: false
        },
        {
          columnName: 'update_time',
          columnType: 'date',
          columnLength: 64,
          columnComment: '更新时间',
          required: true,
          editing: false
        },
        {
          columnName: 'remark',
          columnType: 'text',
          columnLength: -1,
          columnComment: '备注',
          required: false,
          editing: false
        }
      ]
    });
    const selectedSystemUsers = ref([]);
    const rules = reactive({
      loginName: [{required: true, message: '请输入登录名', trigger: 'blur'},
        {min: 3, max: 100, message: '长度在 3 到 100 个字符', trigger: 'blur'}],
      loginPswd: [{required: true, message: '请输入密码', trigger: 'blur'},
        {min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur'}],
      userName: [{required: true, message: '用户姓名', trigger: 'change'}],
    });
    const najlFormRef = ref(null);
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    });

    const fetchSystemUsers = async (params = {}) => {
      try {
        const response = await axios.post(`${process.env.VUE_APP_API_BASE_URL}/systemUser/listPage`, {
          ...params,
          pageNum: pagination.currentPage,
          pageSize: pagination.pageSize
        });
        if (response.data.success) {
          systemUser.value = response.data.data.list;
          pagination.total = response.data.data.total;
        } else {
          console.error('Request failed:', response.data.message);
        }
      } catch (error) {
        console.error('Failed to fetch systemUser:', error);
      }
    };
    const onSearch = () => {
      fetchSystemUsers({
        userName: searchForm.userName,
        remark: searchForm.remark,
        pageNum: pagination.currentPage,
        pageSize: pagination.pageSize
      });
    };

    const handleSizeChange = (newSize) => {
      pagination.pageSize = newSize;
      fetchSystemUsers();
    };

    const handleCurrentChange = (newPage) => {
      pagination.currentPage = newPage;
      fetchSystemUsers();
    };

    const showDialog = (visibleName, formObj, srcData) => {
      const visibilityMap = {addOrEditVisible};
      visibilityMap[visibleName].value = true;
      nextTick(() => {
        if (srcData != undefined) Object.assign(formObj, srcData);
      });
    };
    const closeDialog = (visibleName) => {
      const visibilityMap = {addOrEditVisible};
      visibilityMap[visibleName].value = false;
      najlFormRef.value.resetFields();
      najlForm.userId = 0;
    };
    const validForm = async (najlFormRef) => {
      const valid = await new Promise((resolve) => {
        najlFormRef.value.validate((valid) => {
          resolve(valid);
        });
      });
      if (!valid) {
        ElMessageBox.alert('数据验证失败，请检查输入内容是否正确！！！');
        return false;
      }
      return valid;
    };
    const dalinConfirm = async (name, callback) => {
      ElMessageBox.confirm(
          `您确定要删除 "${name}" 吗？`,
          '警告',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(() => {
        callback();
      }).catch(() => {
        // 用户取消删除
      });
    };

    const reqDeal = async (url, reqType, reqParams, callback) => {
      url = `${process.env.VUE_APP_API_BASE_URL}` + url;
      try {
        let response;
        if (reqType === 'post') {
          response = await axios.post(url, reqParams);
        } else if (reqType === 'get') {
          response = await axios.get(url, {params: reqParams});
        } else if (reqType === 'delete') {
          response = await axios.delete(url);
        } else {
          throw new Error('Unsupported request type');
        }
        callback(response);
      } catch (error) {
        console.error('Request failed:', error);
      }
    };

    const addOrUpdate = async () => {
      if (!await validForm(najlFormRef)) return;
      await reqDeal('/systemUser/addOrUpdate', 'post', najlForm, () => {
        addOrEditVisible.value = false;
        refreshSystemUsers();
      });
    };
    const deleteData = async (userId, userName) => {
      alert(userId)
      dalinConfirm(userName, () => {
        reqDeal(`/systemUser/delete/${userId}`, 'delete', najlForm, () => {
          systemUser.value = systemUser.value.filter(systemUser => systemUser.userId !== userId);
          refreshSystemUsers();
        });
      });
    };
    const deleteDatas = async () => {
      if (selectedSystemUsers.value.length === 0) {
        ElMessageBox({message: '请选择要删除的记录', type: 'warning'});
        return;
      }
      // 构建提示信息
      const names = selectedSystemUsers.value.map(systemUser => systemUser.userName).join(', ');
      dalinConfirm(names, () => {
        const ids = selectedSystemUsers.value.map(systemUser => systemUser.userId);
        reqDeal(`/systemUser/deleteByIds`, 'post', ids, () => {
          systemUser.value = systemUser.value.filter(systemUser => !ids.includes(systemUser.userId));
          refreshSystemUsers();
        });
      });
    };

    const testConnection = async () => {
      if (selectedSystemUsers.value.length === 0) {
        ElMessageBox({message: '请选择要操作的记录', type: 'warning'});
        return;
      }
      const ids = selectedSystemUsers.value.map(systemUser => systemUser.id);
      reqDeal(`/systemUser/connectTest/`, 'post', {"ids": ids}, (response) => {
        console.log("Response:", response.data); // 输出响应数据到控制台
        if (response.data.success) {
          ElMessageBox.alert(response.data.data, '提示', {type: 'success'});
        }
      });
    };

    const showAddTableDialog = () => {
      if (selectedSystemUsers.value.length === 0 || selectedSystemUsers.value.length > 1) {
        ElMessageBox({message: '请选择要操作的记录且只能选择一条记录', type: 'warning'});
        return;
      }
      addTableVisible.value = true;
    };

    const addField = () => {
      tableForm.dbColumnReqList.push({
        columnName: '',
        columnType: '',
        columnLength: '',
        columnComment: '',
        required: false,
        editing: true
      });
    };
    const copyField = (index) => {
      const newField = {...tableForm.dbColumnReqList[index], editing: true};
      tableForm.dbColumnReqList.splice(index + 1, 0, newField);
    };
    const removeField = (index) => {
      tableForm.dbColumnReqList.splice(index, 1);
    };

    const addTable = async () => {
      tableForm.dbId = selectedSystemUsers.value[0].id;
      try {
        reqDeal(`/systemUser/addTable/`, 'post', tableForm, (response) => {
          console.log("Response:", response.data); // 输出响应数据到控制台
          if (response.data.success) {
            ElMessageBox.alert(response.data.data, '提示', {type: 'success'});
          }
        });
        // addTableVisible.value = false;
      } catch (error) {
        console.error('Failed to add table:', error);
      }
    };

    const syncForward = async () => {
      try {
        const response = await axios.post(`${process.env.VUE_APP_API_BASE_URL}/systemUser/syncDb`, selectedSystemUsers.value);
        if (response.data.success) {
          ElMessageBox.alert('正向同步成功', '提示', {
            type: 'success'
          });
        } else {
          ElMessageBox.alert('正向同步失败', '提示', {
            type: 'error'
          });
        }
      } catch (error) {
        console.error('Failed to sync forward:', error);
      }
    };

    const syncBackward = async () => {
      try {
        const response = await axios.post(`${process.env.VUE_APP_API_BASE_URL}/systemUser/backwardSyncDb`, selectedSystemUsers.value);
        if (response.data.success) {
          ElMessageBox.alert('反向同步成功', '提示', {
            type: 'success'
          });
        } else {
          ElMessageBox.alert('反向同步失败', '提示', {
            type: 'error'
          });
        }
      } catch (error) {
        console.error('Failed to sync backward:', error);
      }
    };

    const refreshSystemUsers = () => {
      fetchSystemUsers();
    };

    const resetForm = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''; // 将所有值设置为空字符串
        // 如果字段类型不同，可以在这里添加更多的逻辑来处理不同的初始值
      });
      refreshSystemUsers();
    };
    const handleTableMaintain = (slectedRow) => {
      tableMaintain.value.showEditDialog(slectedRow);
    };

    const addTableVisible = ref(false);

    onMounted(() => {
      fetchSystemUsers(); // 页面加载时立即获取用户列表
    });

    return {
      zhCn,
      tableMaintain,
      najlFormRef,
      systemUser,
      searchForm,
      addOrEditVisible,
      najlForm,
      tableForm,
      selectedSystemUsers,
      rules,
      fetchSystemUsers,
      onSearch,
      showDialog,
      handleTableMaintain,
      closeDialog,
      addOrUpdate,
      deleteData,
      deleteDatas,
      testConnection,
      showAddTableDialog,
      addField,
      copyField,
      removeField,
      addTable,
      syncForward,
      syncBackward,
      refreshSystemUsers,
      resetForm,
      addTableVisible,
      pagination,
      handleSizeChange,
      handleCurrentChange
    };
  }
};
</script>


<style scoped>
.el-select {
  width: 100%; /* 确保下拉框宽度足够 */
}

/* Make inputs take full width of their container */
.search-form :deep(.el-input) {
  width: 100%;
}

.header-row {
  display: flex;
  gap: 20px; /* 增加间距 */
  margin-bottom: 24px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.header-row .el-form-item {
  margin-right: 0;
  width: 100%;
}

.styled-input :deep(.el-input__wrapper) {
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 6px;
  transition: all 0.3s ease;
}

.styled-input :deep(.el-input__wrapper:hover) {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.styled-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

/* 调整标签样式 */
.header-row .el-form-item :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

/* 移除对话框的内边距 */
.full-width-dialog :deep(.el-dialog__body) {
  padding: 10px !important;
}

/* 确保表格内容占满宽度 */
.field-list-container {
  width: 100%;
  padding: 0;
}

/* 调整表格列的宽度 */
:deep(.el-table) {
  width: 100% !important;
  margin: 0;
}

/* 调整页脚按钮区域的内边距 */
:deep(.el-dialog__footer) {
  padding: 10px 20px;
}
</style>